import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:redux/redux.dart';
import 'package:stock_check/common/dao/WorksDao.dart';
import 'package:stock_check/common/db/ITModel.dart';
import 'package:stock_check/common/db/InstitutionModel.dart';
import 'package:stock_check/common/db/SqliteManage.dart';
import 'package:stock_check/common/model/app.dart';
import 'package:stock_check/common/model/checkITDeviceItem.dart';
import 'package:stock_check/common/model/checkITDeviceItemDetail.dart';
import 'package:stock_check/common/model/checkInstitutionDetail.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/MyScaffold.dart';

class CheckDevicesWorkPage extends StatefulWidget {
  final String tab;
  const CheckDevicesWorkPage({Key key, this.tab}) : super(key: key);
  @override
  _CheckDevicesWorkPageState createState() => _CheckDevicesWorkPageState();
}

class _CheckDevicesWorkPageState extends State<CheckDevicesWorkPage> {
  bool checkAllIT = false; // 选中所有it类设备
  bool checkInstitution = false; // 选中所有设施类设备
  List<CheckITDeviceItem> itList = new List();
  List<CheckITDeviceItem> institutions = new List();
  Store<StockState> store;
  final formatter = new DateFormat('yyyy-MM-dd');


  // 开始下载数据
  _startDownload(String tab) async{
      String currentTime = formatter.format(DateTime.now());
      List<CheckITDeviceItem> needDownLoad = new List<CheckITDeviceItem>();
      if(tab == 'IT类'){
        // 下载IT数据
        _downLoadIT(currentTime,needDownLoad);
      }else{
        _downLoadInstitution(currentTime,needDownLoad);
      }
  }

  Widget _renderHead(App appInfo,String tab) {
    bool online = appInfo.netWork.index != 2;
    Color accentColor = Theme.of(context).primaryColor;
    accentColor = accentColor == Color(0xff212121) ? Colors.blue : accentColor;
    return Card(
        margin: EdgeInsets.zero,
        shape: RoundedRectangleBorder(),
        elevation: .7,
        child: ListTile(
          dense: true,
            contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
            leading: Checkbox(
                value: tab=='IT类'?checkAllIT:checkInstitution,
                onChanged: (bool) {
                  setState(() {
                    if(tab=='IT类'){
                      checkAllIT = bool;
                      itList.forEach((CheckITDeviceItem w) {
                        if (w.ifDownloadStr=='未下载') w.check = bool;
                      });
                    }else{
                      checkInstitution = bool;
                      institutions.forEach((CheckITDeviceItem w){
                        if (w.ifDownloadStr=='未下载') w.check = bool;
                      });
                    }
                  });
                }),
            title: Text("全选"),
            trailing: OutlineButton(
              borderSide: BorderSide(
                color: Colors.blue,
                width: 2.0
              ),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
              onPressed: online ? ()=>_startDownload(tab) : null,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(
                    Icons.cloud_download,
                    color: Colors.blue,
                  ),
                  Text(
                    online ? " 下载" : " 离线",
                    style: TextStyle(color: Colors.blue),
                  ),
                ],
              ),
            )
        )
    );
  }

  // 刷新数据
  Future<Null> _pullToRefresh() async {
    Fluttertoast.showToast(msg: "数据已刷新!");
    return null;
  }

  _renderList(appInfo,list,type) {
    if(list.length>0)
    return RefreshIndicator(
        onRefresh: _pullToRefresh,
        child: Scrollbar(child: ListView.separated(
          shrinkWrap: true,
          itemCount: list.length,
          separatorBuilder: (context,index){
            return Divider();
          },
          itemBuilder: (context,index){
            return Column(
              children: <Widget>[
                ListTile(
                  dense: true,
                  onTap: list[index].ifDownloadStr == '已下载' ? () {
                    NavigatorUtils.goNeedCheckDeviceListPage(context,list[index], type);
                  } : null,
                  contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 0.0),
                  leading: Checkbox(
                      value: list[index].check,
                      onChanged: (bool) {
                        setState(() {
                          list[index].check =
                          list[index].ifDownloadStr == '已下载' ? false : bool;
                        });
                      }),
                  title: Text(
                    "${list[index].startTimeStr}-${list[index].planName}",
                    style: TextStyle(
                        color: list[index].ifDownloadStr != '已下载'
                            ? Colors.grey
                            : Theme.of(context).accentColor,
                        fontSize: 15.0),
                  ),
                  trailing: list[index].ifDownloadStr=='已下载' ?CommonsWidget.hasDownLoad : CommonsWidget.notDownload,
                )
              ],
            );
          },
        ))
    );
    else
      return CommonsWidget.getNullData();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    store = StoreProvider.of(context);
    itList = store.state.worksInfo.checkITDevices;
    institutions = store.state.worksInfo.institutions;
  }

  final List<Tab> tabs = <Tab>[
    new Tab(text: 'IT类',),
    new Tab(text: '设施类'),
  ];

  Widget getContainer(tab,appInfo){
    return Container(
        child: Column(
          children: [
            Column(
              children: [_renderHead(appInfo,tab)],
            ),
            Padding(padding: EdgeInsets.only(top: 8.0),),
            Expanded(
              child: _renderList(appInfo,tab=='IT类'?itList:institutions,tab),
            )
          ],
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return StoreBuilder<StockState>(builder: (context, store) {
      App appInfo = store.state.appInfo;
      return MyScaffold(
          title: Text("巡检任务"),
          store: store,
          noLeading: true,
          child:getContainer(widget.tab,appInfo),
      );
//      var widget = MyScaffold(
//          title: Text("巡检任务"),
//          store: store,
//          noLeading: true,
//          bottom: TabBar(
//              tabs: tabs,
//              indicatorColor: Colors.white,
//              indicatorSize: TabBarIndicatorSize.label,
//          ),
//          child: TabBarView(children: tabs.map((tab){
//            return getContainer(tab.text,appInfo);
//          }).toList())
//      );
//      return DefaultTabController(length: tabs.length, child: widget);
    });
  }




////////////////////////////////////下载方法/////////////////////////////////////////////

  //下载IT数据
  _downLoadIT(String currentTime,List<CheckITDeviceItem> needDownLoad)async{
    itList.forEach((w) {
      if (w.check == true) {
        needDownLoad.add(w);
      }
    });
    if (needDownLoad.length == 0) {
      Fluttertoast.showToast(msg: "暂无可下载数据！");
      setState(() {
        checkAllIT = false;
      });
    }else{
      List<CheckITDeviceItemDetail> list = new List();
      CommonsWidget.showLoadingDialog(context,'下载中...');
      try{
        // 根据id下载所有数据
        for(int i=0;i<needDownLoad.length;i++){
          var res = await WorksDao.downloadITCheckItemByRecordID(needDownLoad[i].recordId);
          list.add(res);
        }
      }catch(e){
        Navigator.of(context,rootNavigator: true).pop(context);
        Fluttertoast.showToast(msg: '服务器错误！！');
        return;
      }

      if(list.length==0){
        Fluttertoast.showToast(msg: '未下载到数据');
        return;
      }

      list.forEach((CheckITDeviceItemDetail m){
        // 更新局部数据
        itList.forEach((item){
          if(m.recordId == item.recordId){
            item.ifDownloadStr = '已下载';
            item.check = false;
          }
        });
      });

      DataBase dataBase = new DataBase();
      var count = await dataBase.getITCount();
      ITModel itModel = new ITModel();
      // 判断新老数据
      List<CheckITDeviceItemDetail> oldList = new List();
      itModel = await dataBase.getOneITByUpdateTime(currentTime);
      if(itModel!=null&&itModel.jsonTxt!=null){
        String oldData = itModel.jsonTxt;
        var oldJsonList = json.decode(oldData);
        for(int i=0;i<oldJsonList.length;i++){
          oldList.add(CheckITDeviceItemDetail.fromJson(oldJsonList[i]));
        }
        List<CheckITDeviceItemDetail> temp = new List();
        list.forEach((CheckITDeviceItemDetail ck){
          bool flag = true;
          oldList.forEach((f){
            if(ck.recordId == f.recordId){
              flag = false;
            }
          });
          if(flag) temp.add(ck);
        });
        oldList = oldList + temp;
        itModel.jsonTxt = json.encode(oldList);
        await dataBase.updateITModel(itModel);
      }else{
        itModel = new ITModel();
        itModel.updateTime = currentTime;
        itModel.jsonTxt = json.encode(list);
        if(count>0){
          await dataBase.deleteTable();
        }
        await dataBase.insertITModel(itModel);
      }
      Navigator.of(context,rootNavigator: true).pop(context);
      setState(() {
        checkAllIT = false;
      });
    }
  }

  // 下载设施设备
  void _downLoadInstitution(String currentTime, List<CheckITDeviceItem> needDownLoad) async{
    institutions.forEach((w) {
      if (w.check == true) {
        needDownLoad.add(w);
      }
    });
    if (needDownLoad.length == 0) {
      Fluttertoast.showToast(msg: "暂无可下载数据！");
      setState(() {
        checkInstitution = false;
      });
    }else{
      List<CheckInstitutionDetail> list = new List();
      CommonsWidget.showLoadingDialog(context,'下载中...');
      try{
        // 根据id下载所有数据
        for(int i=0;i<needDownLoad.length;i++){
          var res = await WorksDao.downloadInstitutionByRecordID(needDownLoad[i].recordId);
          list.add(res);
        }
      }catch(e){
        Navigator.of(context,rootNavigator: true).pop(context);
        Fluttertoast.showToast(msg: '服务器错误！！');
        return;
      }

      if(list.length==0){
        Fluttertoast.showToast(msg: '未下载到数据');
        return;
      }

      list.forEach((CheckInstitutionDetail m){
        // 更新局部数据
        institutions.forEach((item){
          if(m.recordId == item.recordId){
            item.ifDownloadStr = '已下载';
            item.check = false;
          }
        });
      });

      DataBase dataBase = new DataBase();
      var count = await dataBase.getInstitutionCount();
      InstitutionModel model = new InstitutionModel();
      // 判断新老数据
      List<CheckInstitutionDetail> oldList = new List();
      // 获取今天下载的数据
      model = await dataBase.getOneInstitutionByUpdateTime(currentTime);
      if(model!=null&&model.jsonTxt!=null){
        String oldData = model.jsonTxt;
        var oldJsonList = json.decode(oldData);
        for(int i=0;i<oldJsonList.length;i++){
          oldList.add(CheckInstitutionDetail.fromJson(oldJsonList[i]));
        }
        List<CheckInstitutionDetail> temp = new List();
        list.forEach((CheckInstitutionDetail ck){
          bool flag = true;
          oldList.forEach((f){
            if(ck.recordId == f.recordId){
              flag = false;
            }
          });
          if(flag) temp.add(ck);
        });
        oldList = oldList + temp;
        model.jsonTxt = json.encode(oldList);
        await dataBase.updateInstitutionModel(model);
      }else{
        model = new InstitutionModel();
        model.updateTime = currentTime;
        model.jsonTxt = json.encode(list);
        if(count>0){
          await dataBase.deleteTable();
        }
        await dataBase.insertInstitutionModel(model);
      }
      Navigator.of(context,rootNavigator: true).pop(context);
      setState(() {
        checkInstitution = false;
      });
    }
  }
}
